<?php
class ZhaopinAction extends CommonAction
{

    private $table_name;
    public function __construct()
    {

        $this->table_name = "Zhaopin";
        parent::__construct();
    }

    public function index()
    {
        if (isset($_GET['spread']) && $_GET['spread'] == 1) {
            $count = M($this->table_name)->where('spread_sort > 0')->count();
        } else {
            $count = M($this->table_name)->count(); // 查询总数据记录
        }

        import('ORG.Util.Page');

        $count = M($this->table_name)->count(); // 查询总数据记录

        $Page = new Page($count, C('PAGESIZE'));

        $show = $Page->show();

        $temp = M($this->table_name);
        if (isset($_POST['keywords'])) {
            $map['title'] = array('like', '%' . $_POST['keywords'] . '%');
            $temp         = $temp->where($map);
        }

        if (isset($_GET['spread']) && $_GET['spread'] == 1) {
            $spread['spread_sort'] = array('GT', 0);
            $temp                  = $temp->where($spread);
        }

        $temp = $temp->order("createtime DESC")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($temp as $v) {
            $v['uname'] = M('user')->where('uid=' . $v['uid'])->getField('username');
            $v['city']  = M('city')->where(array('id' => $v['cityid']))->getField("city");
            $list[]     = $v;
        }

        $this->assign("list", $list);

        $this->assign("page", $show);

        $this->display();
    }

    public function add()
    {

        if (isset($_POST['submit'])) {
            $data               = $_POST;
            $data['createtime'] = mktime();
            $data['status']     = 1;
            if (M($this->table_name)->add($data)) {
                $this->success("操作成功！", U('index'));
            } else {

                $this->error("操作失败");
            }
        } else {
            $this->list = M($this->table_name . "Cate")->select();
            $this->display();
        }

    }

     function add_batch(){
         set_time_limit(0);
         if(isset($_POST['submit'])){
             $data = $_POST;
             $data['createtime']=mktime();
             $data['status']= 1 ;
             $title_city = $_POST['title_city']; //标题城市
             $title_rhetoric = $_POST['title_rhetoric']; //分类修辞
             $title_ending = $_POST['title_ending']; //标题结尾
             $class_type = $_POST['class_type']; //所属分类
             $username   =


             $title_city_arr = explode(',', $title_city);
             $title_rhetoric_arr = explode(',', $title_rhetoric);
             $title_ending_arr = explode(',', $title_ending);
             //$class_type_arr = explode(',', $class_type);
             $class_type_arr = $class_type;
             $data = $this->insertAll();
             if ($data['error'] != 0)
             {
                 $this->error('发布失败: '.$data['msg']);
             } else {
                 $this->success('发布成功',U('index'));
             }

         }else{
             $this->assign('Categories', M('category')->where(array('status'=>1))->select());
             $this->assign('CityLimit', $this->getArticleLmit());
             $this->display();
         }

     }

     private function insertAll()
     {

         $photos = $_SESSION['adminUploaders'];
         $post = $data          = $_POST;
         $post['createtime']    = mktime();
         $post['status']        = 1 ;

         $title_city            = $data['title_city']; //标题城市
         $city_limit            = trim($data['city_limit']);//城市区域文章数量限制
         $city_limit            = empty($city_limit) ? 10 : intval($city_limit);
         $title_rhetoric        = $data['title_rhetoric']; //分类修辞
         $title_ending          = $data['title_ending']; //标题结尾
         $class_type            = $data['class_type']; //所属分类
         $headerContent         = $data['header_content']; //头部内容
         $middleContent         = $data['middle_content']; //中部内容
         $tailContent          = $data['tail_content'];  //尾部内容
         $username               = $data['username'];
         $wx                     = $data['weixin'];  //微信咨询
         $perform                = $data['perform']; //场次
         $uid = M('user')->where(array('username'=> $username))->getField('uid');
         if(!$uid)
         {
             return array(
                 'msg' => '用户不存在',
                 'error' => '1'
             );
         }

         //设置cookie
         if($this->getArticleLmit() != $city_limit)
         {
             $this->getArticleLmit($city_limit);
         }

         $titleCityArr        = array_filter(explode(',', str_replace('，', ',', trim($title_city))));
         $titleRhetoricArr    = array_filter(explode(',', str_replace('，', ',', trim($title_rhetoric))));
         $titleEndingArr      = array_filter(explode(',', str_replace('，', ',', trim($title_ending))));
         $headerContentArr    = array_filter(explode('{##}', $headerContent));
         $middleContentArr    = array_filter(explode('{##}', $middleContent));
         $tailContentArr      = array_filter(explode('{##}', $tailContent));
         $classTypeArr        = $class_type;



         $data = arrayZuHe(array(
             $titleCityArr,
             $titleRhetoricArr,
             $titleEndingArr
         ));

         $data1 = arrayZuHe(array(
             $headerContentArr,
             $middleContentArr,
             $tailContentArr
         ));

         if (empty($data) || empty($data1))
         {
             return array(
                 'error' => 1,
                 'msg'   => '组合失败'
             );
         }

         //所有数据组合
         $newArr  = array();
         $i = 0;
         foreach ($data[0] as $key=>$title)
         {
             //标题内容 数量大于 内容数量
             if (count($data[0]) > count($data1[0]))
             {
                 //如果内容不够补
                 if (!isset($data1[0][$key]))
                 {
                     if ($i > count($data1[0]) - 1)
                     {
                         $i = 0;
                     }
                     //索引从头再补
                     $newArr[] = $title."{##}".$data1[0][$i];
                     $i ++ ;
                 } else {
                     $newArr[] = $title."{##}".$data1[0][$key];
                 }
             } else {
                 $newArr[] = $title."{##}".$data1[0][$key];
             }
         }

         if (empty($newArr))
         {
             return array(
                 'error' => 1,
                 'msg'   => '组合失败'
             );
         }

         $insertArr = array();

         $citys          = array();
         $areas          = array();

         $cityIdsData = M('city')->where(array(
             'province' => array('in', implode(',', $titleCityArr))
         ))->select();
         $cityIdsData1 = M('city')->where(array(
             'city' => array('in', implode(',', $titleCityArr))
         ))->select();
         $areaIdsData = M('area')->where(array(
             'city'  => array('in', implode(','), $titleCityArr)
         ))->select();
         foreach ($cityIdsData as $city)
         {
             $citys[$city['province']] = $city['id'];
         }
         foreach ($cityIdsData1 as $city)
         {
             $citys[$city['city']] = $city['id'];
         }

         foreach ($areaIdsData as $area)
         {
             $areas[$area['name']] = $area;
         }

         shuffle($newArr);
         shuffle($photos);
         $photo_i = 0;
         foreach ($newArr as $value)
         {
             $value = explode('{##}', $value);
             list(
                 $city,
                 $titleR,
                 $titleEn,
                 $headContent,
                 $midContent,
                 $tailContent
                 ) = $value;
             $headContent = stripslashes($headContent);
             $midContent = stripslashes($midContent);
             $tailContent = stripslashes($tailContent);
             $tempCity   = isset($citys[$city]) ? $citys[$city] : "";
             $areaid     = 0;
             //如果城市为空，从地区找
             if (empty($tempCity))
             {
                 $tempCity   = isset($areas[$city]) ? $areas[$city]['cityid'] : "";
                 $areaid     = isset($areas[$city]) ? $areas[$city]['id'] : "";
             }
             if (!empty($tempCity))
             {
                 //如果图片设为重复，则重头开始匹配
                 if ($post['photo_repeat'] == 1 && $photo_i > count($photos))
                 {
                     $photo_i = 0;
                 }
                 $photo = isset($photos[$photo_i]) ? $photos[$photo_i] : "";

                 $insertArr[$city.$titleR.$titleEn] = array(
                     'uid'           => $uid,
                     'cid'          => $classTypeArr[0],
                     'areaid'      => $areaid,
                     'cityid'      => $tempCity,
                     'title'    => $city.$titleR.$titleEn,
                     'keywords' => $city.", $titleR, $titleEn",
                     'content'  => "$headContent $midContent $tailContent",
                     'status'   => $post['status'],
                     'createtime'=> $post['createtime'],
                     'shopname' => $post['shopname'],
                     'contact'  => $post['contact'],
                     'phone'    => $post['phone'],
                     'email'    => $post['email'],
                     'qq'       => $post['qq'],
                     'swt'      => $post['swt'],
                     'cover'     => $photo,
                     'is_batch'  => 1,
                     'perform'   => $perform,
                     'weixin'    => $wx
                 );
                 $photo_i ++ ;
             }

         }
         $insertArr = $this->articleLimit($city_limit, $insertArr);
         if (!empty($insertArr))
         {
             $res = array();
             $db = M($this->table_name);
             $db->startTrans();

             //分组插入，分担压力
             $preInsert = array_chunk($insertArr, 100);
             foreach ($preInsert as $value)
             {
                 $res[] = $db->addAll(array_values($value));
             }

             //插入失败则回滚
             foreach ($res as $result)
             {
                 if (!$result)
                 {
                     $db->rollback();
                     return array(
                         'error'    => 1,
                         'msg'      => '数据库错误，请稍后操作'
                     );
                     break;
                 }
             }
             //提交插入
             $db->commit();
             $_SESSION['adminUploaders'] = null;
             return array(
                 'count'    => count($insertArr),
                 'error'    => 0
             );
         } else {
             return array(
                 'error'    => 1,
                 'msg'      => '城市不正确，请检查'
             );
         }
     }

     private function getArticleLmit($value = '')
     {
         $cookieFile = './AdminArticleLimit.txt';
         $cookieName = 'AdminArticleLimit';
         if (!empty($value))
         {
             //储存limit
             cookie($cookieName, $value);
             $fp = fopen($cookieFile, "w");
             fwrite($fp, $value);
             fclose($fp);
         } else {
             $cookieValue = cookie($cookieName);
             if (empty($cookieValue))
             {
                 $cookieValue = file_get_contents($cookieFile);
             }
             return $cookieValue;
         }
     }

     private function articleLimit($number, $article)
     {
         $data   = array();
         $result = array();
         foreach($article as  $value)
         {
             //城市-地区 数量>$number，则跳过
             if (
                 isset($data[$value['cityid'].'-'.$value['areaid']])
                 && count($data[$value['cityid'].'-'.$value['areaid']]) > ($number - 1)
             )
             {
                 continue;
             }
             $data[$value['cityid'].'-'.$value['areaid']][] = $value;
         }
         foreach($data as $value)
         {
             foreach($value as $article)
             {
                 $result[] = $article;
             }
         }
         return $result;
     }

     public function uploadAll()
     {
         //先删除以前的
         if (!empty($_SESSION['adminUploaders']))
         {
             foreach ($_SESSION['adminUploaders'] as $photo)
             {
                 if (file_exists('.'.$photo))
                 {
                     @unlink('.'.$photo);
                 }
             }
         }

         $photos = array();
         import('ORG.Net.UploadFile');
         $upload = new UploadFile();// 实例化上传类
         $upload->maxSize  = 3145728 ;// 设置附件上传大小
         $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
         $path=date("Ym").'/';
         $upload->savePath =  './Data/photo/'.$path;// 设置附件上传目录
         if(!file_exists("./Data/photo/".$path)){
             mkdir("./Data/photo/".$path);
         }
         if(!$upload->upload()) {// 上传错误提示错误信息
             return $this->ajaxReturn(array(
                 'error' => '1',
                 'msg'   => $upload->getErrorMsg()
             ));
         }else{// 上传成功 获取上传文件信息
             $info =  $upload->getUploadFileInfo();
             foreach ($info as $p)
             {
                 $photos[] = trim($p['savepath'], '.').$p['savename'];
             }
         }
         $_SESSION['adminUploaders'] = $photos;
         return $this->ajaxReturn(array(
             'error' => '0',
             'msg'   => '上传成功'
         ));
     }

    /**

     *

     * 编辑文章

     */

    public function edit()
    {
        $id = htmlspecialchars($_GET['id']);
        if (is_numeric($id)) {
            if (isset($_POST['submit'])) {
                $data = $_POST;
                // $data['createtime']=mktime();
                $data['cityid'] = I('post.city');
                M($this->table_name)->where("id=" . $id)->save($data);
                $this->success("更新成功！", U('index'));
            } else {
                $province = M('City')->where("status=0 AND province !='' ")->select();
                $this->assign("province", $province);

                $this->list = M("category")->select();
                $li         = M($this->table_name)->where("id=" . $id)->find();
                $this->assign("li", $li);

                $city = M('City')->where("id = " . $li['cityid'])->find();
                $this->assign("city", $city);

                $citys = M('City')->where("cid = " . $city['cid'])->select();
                $this->assign("citys", $citys);

                $this->display();
            }

        }
    }

    /**

     * 删除

     *

     */

    public function del()
    {
        $qstr = $_GET['qstr'];

        $data = M($this->table_name);
        if (isset($qstr)) {
            $arr = explode(",", $qstr);

            foreach ($arr as $val) {

                $data->where("id=$val")->delete();

            }
            $this->success("删除成功！", U('index'));

        } else {

            if (isset($_GET['id'])) {

                $data->where("id=" . $_GET['id'])->delete();

                $this->success("删除成功！", U('index'));

            } else {

                $this->error("请选择要删除的ID");

            }

        }

    }

    public function shenhe()
    {
        $id       = htmlspecialchars($_GET['id']);
        $xzh_post = htmlspecialchars($_GET['xzh_post']);
        //$this->success("操作成功！",U('index'));
        if ($xzh_post == 1) {
            $li          = M($this->table_name)->where("id=" . $id)->find();
            $city_pinyin = M('city')->where('id=' . $li['cityid'])->getField('pinyin');
            $cate_pinyin = M('category')->where('id=' . $li['cid'])->getField('path');

            $url = "https://mip.yecxx.com/" . $city_pinyin . "/" . $cate_pinyin . "/" . $id . ".html";

            //$this->success("操作成功！".$url,U('index'));

            M('Zhaopin')->where("id=" . $_GET['id'])->setField('status', 1);
            M('Zhaopin')->where("id=" . $_GET['id'])->setField('xzh_post', 1);

            if ($url) {
                $urls    = array($url);
                $api     = 'http://data.zz.baidu.com/urls?appid=1601448235506981&token=1IQVJVW0CIsNOFTC&type=realtime';
                $ch      = curl_init();
                $options = array(
                    CURLOPT_URL            => $api,
                    CURLOPT_POST           => true,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POSTFIELDS     => implode("\n", $urls),
                    CURLOPT_HTTPHEADER     => array('Content-Type: text/plain'),
                );
                curl_setopt_array($ch, $options);
                $result = curl_exec($ch);
                $this->success("操作成功！推送结果：" . $result, U('index'));
            } else {
                $this->success("操作成功！", U('index'));
            }

            //$this->redirect('index');

        } elseif ($xzh_post == 2) {
            $li          = M($this->table_name)->where("id=" . $id)->find();
            $city_pinyin = M('city')->where('id=' . $li['cityid'])->getField('pinyin');
            $cate_pinyin = M('category')->where('id=' . $li['cid'])->getField('path');

            $url = "https://mip.yecxx.com/" . $city_pinyin . "/" . $cate_pinyin . "/" . $id . ".html";

            //$this->success("操作成功！".$url,U('index'));

            M('Zhaopin')->where("id=" . $_GET['id'])->setField('status', 1);
            M('Zhaopin')->where("id=" . $_GET['id'])->setField('xzh_post', 1);

            if ($url) {
                $urls    = array($url);
                $api     = 'http://data.zz.baidu.com/urls?appid=1601448235506981&token=1IQVJVW0CIsNOFTC&type=original';
                $ch      = curl_init();
                $options = array(
                    CURLOPT_URL            => $api,
                    CURLOPT_POST           => true,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POSTFIELDS     => implode("\n", $urls),
                    CURLOPT_HTTPHEADER     => array('Content-Type: text/plain'),
                );
                curl_setopt_array($ch, $options);
                $result = curl_exec($ch);
                $this->success("操作成功！推送结果：" . $result, U('index'));
            } else {
                $this->success("操作成功！", U('index'));
            }
        } elseif ($xzh_post == 123) {
            $startID = 33001;
            $endID   = 34000;

            $list     = M('Zhaopin')->where("status=1 and id BETWEEN " . $startID . " AND " . $endID)->select();
            $list_url = "";
            foreach ($list as $item) {
                //echo $item,'<br />';
                $city_pinyin = M('city')->where('id=' . $item['cityid'])->getField('pinyin');
                $cate_pinyin = M('category')->where('id=' . $item['cid'])->getField('path');
                $url         = "https://mip.yecxx.com/" . $city_pinyin . "/" . $cate_pinyin . "/" . $item['id'] . ".html\n";
                $list_url .= $url;
                //echo "zhaopin-2001-3000";
            }
            echo $startID . "-" . $endID;
            $myfile = fopen("./zhaopin-" . $startID . "-" . $endID . ".txt", "w");
            fwrite($myfile, $list_url);
            fclose($myfile);
            // $this->success("操作成功！\n".$list_url,U('index'));

        } else {
            M('Zhaopin')->where("id=" . $_GET['id'])->setField('status', 1);
            $this->success("审核成功！");
        }

    }

    public function read()
    {
        $id = htmlspecialchars($_GET['id']);
        if (is_numeric($id)) {
            $li       = M($this->table_name)->where("id=" . $id)->find();
            $cityname = M('city')->where('id=' . $li['cityid'])->getField('city');
            $username = M('User')->where('uid=' . $li['uid'])->getField('username');
            $this->assign('li', $li);
            $this->assign('username', $username);
            $this->assign('cityname', $cityname);
            $this->display();
        }

    }

    public function spreadSort()
    {
        $id                  = $_POST['id'];
        $data['spread_sort'] = intval($_POST['sort']);
        $expired             = trim($_POST['expired_at']);
        if (!empty($expired)) {
            $data['spread_sort_time'] = date('Y-m-d H:i:s', strtotime($expired));
        }
        M('Zhaopin')->where('id=' . $id)->setField($data);
        $this->ajaxReturn(1);
    }

}
